package com.firmail.file.service;

import com.firmail.mock.center.api.vo.MockMetadata;
import com.firmail.util.FileKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class FileOpsService {

    @Value("${path.baseDir}")
    private String baseDir="/data/mock/";


    public boolean writeFile(MockMetadata metadata) throws IOException {
        if (metadata!=null){
            if (baseDir!=null&&!baseDir.endsWith("/")){
                baseDir=StringUtils.trim(baseDir)+"/";
            }
            if (StringUtils.isEmpty(baseDir)){
                baseDir="/";
            }
            String fullname= metadata.getRelativePath();
            if (fullname.startsWith("/")){
                fullname=fullname.substring(1);
            }
            fullname=baseDir+fullname;
            String fileextension=metadata.getDataType();

            String data= metadata.getData();
            String method= metadata.getReqMethod();
            // /ois-hr/hr/orgs/get-list
            // /test
            // /aaa
            if (fullname.endsWith("/")){
                fullname =fullname.substring(0, fullname.lastIndexOf("/"));
            }
            String path=fullname.substring(0,fullname.lastIndexOf("/"));
            FileKit.createDir(path);
            if ("json".equalsIgnoreCase(fileextension)){

                //String filename=fullname.substring(fullname.lastIndexOf("/") + 1);
                return FileKit.writeFileContent(fullname+"_"+method+"."+fileextension, data, false);
            }else if ("xml".equalsIgnoreCase(fileextension)){
                return FileKit.writeFileContent(fullname,data,false);
            }
        }
        return false;
    }

    public static void main(String[] args) throws IOException{
        System.out.println("/".substring(1));
        MockMetadata metadata= new MockMetadata();
        metadata.setData("{\"kiju\":\"987\"}");
        metadata.setDataType("xml");
        metadata.setReqMethod("get");
        metadata.setRelativePath("/test/org/list");
        new FileOpsService().writeFile(metadata);
    }
}
